package org.one.stone.soup.grfxML.plugin.swing;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import org.one.stone.soup.grfxML.DataNode;
import org.one.stone.soup.grfxML.DataPoint;
import org.one.stone.soup.grfxML.DataState;
import org.one.stone.soup.grfxML.DataText;
import org.one.stone.soup.grfxML.GrfxMLEngine;
import org.one.stone.soup.grfxML.plugin.SimplePlugin;
import org.one.stone.soup.grfxML.plugin.grfxMLCaster;
import org.one.stone.soup.mjdb.data.field.Field;
import org.one.stone.soup.mjdb.data.field.LockException;

public class JPopupPlugin extends SimplePlugin implements Runnable,ActionListener{
	private static final int TARGET_ARG = 0;
	private static final int OPTIONS_ARG = 1;
	private static final int SHOW_ARG = 2;

	private DataNode target;
	private DataText options = new DataText();
	private DataState show = new DataState();

	private JPopupMenu popup;
/**
 * FileToText constructor comment.
 */
public JPopupPlugin(GrfxMLEngine engine) {
	super(engine);

	target = new DataNode(engine);
}
/**
 * initialize method comment.
 */
public void initialize() {}
/**
 * process method comment.
 */
public void process()
{
 try{
	if(show.getValue()==true)
	{
		new Thread(this).start();
		show.setValue(false,this);
	}
 }catch(LockException le)
 {}
}

public void run()
{
	//try{
		String[] optionList = new String[ options.size() ];
		for(int loop=0;loop<options.size();loop++)
		{
			optionList[loop] = options.get(loop).getValue();
		}

		DataPoint position = target.getTranslation().getPositionView();
		popup = new JPopupMenu();

		JMenuItem item = new JMenuItem( "Option" );
		popup.add(item);
		item.addActionListener( this );

		Point pos = getEngine().getController().getComponent().getLocation();
		popup.setLocation( pos.x+position.getValueX(),pos.y+position.getValueY() );
		popup.setVisible(true);

		//getEngine().getController().getComponent().add( popup );

	//}catch(LockException le)
	//{}
}

/**
 * register method comment.
 */
public void register(org.one.stone.soup.mjdb.data.field.DataLinker store)
{
	target = grfxMLCaster.cast(target,getArg(target,TARGET_ARG,store));
	options = grfxMLCaster.cast(options,getArg(options,OPTIONS_ARG,store));
	show = grfxMLCaster.cast(show,getArg(show,SHOW_ARG,store));
}
public void replace(Field oldObj, Field newObj)
{
	target = grfxMLCaster.replace(target,oldObj,newObj);
	options = grfxMLCaster.replace(options,oldObj,newObj);
	show = grfxMLCaster.replace(show,oldObj,newObj);
}
/**
 * stop method comment.
 */
public void stop() {}

public void actionPerformed(ActionEvent event)
{
	popup.setVisible(false);
	getEngine().getAPI().getMouse().setHeld( target );
	getEngine().getController().sendCommand( event.getActionCommand() );
}

}
